<template>
  <view>
    <TnNavbar fixed back-icon="" home-icon="" :center="false">
      <view class="tn-pl-sm tn-pr-xs tn-flex items-center justify-between" style="height: 100%;position: relative">
        <image @click="showPopup = !showPopup" :src="pmAvatar" style="width: 65rpx; height: 65rpx;border-radius: 100%"></image>
        <input
            style="
              border: 1px solid #eee;
              height: 65rpx;
              border-radius: 65rpx;
              width: calc(100% - 75rpx);
              padding: 0 70rpx 0 50rpx;
            "
            placeholder="名称/ID,点头像筛选更多"
            confirm-type="search"
            @confirm="search"
            v-model="where.def_name"
        >
        <tn-icon name="search" style="position: absolute;left: 110rpx; top: 50%; transform: translateY(-50%)"></tn-icon>
      </view>
    </TnNavbar>
    <TnPopup v-model="showPopup" open-direction="top">
      <view :style="{paddingTop: height + 10 + 'px'}">
        <swiper style="height: 450px;width: 100%" @change="cardSwiper" :circular="true">
          <swiper-item>
            <view class="cu-bar">
              <view class="action sub-title">
                <text class="text-xl text-bold text-blue">种族值排序</text>
                <text class="text-ABC text-blue">sort</text>
              </view>
            </view>
            <view class="padding-lr-sm flex justify-between flex-wrap align-center">
              <button
                  class="text-sm margin-bottom-sm"
                  :class="item.order === where.order && item.sort === where.sort ? 'bg-blue' : 'bg-blue light'"
                  style="width: 22%"
                  v-for="item in filterList"
                  @click="chooseFilter(item)"
              >
                {{ item.name }}
              </button>
            </view>
          </swiper-item>
          <swiper-item>
            <view class="cu-bar">
              <view class="action sub-title">
                <text class="text-xl text-bold text-blue">种类</text>
                <text class="text-ABC text-blue">kind</text>
              </view>
            </view>
            <view class="padding-lr-sm flex justify-between flex-wrap align-center">
              <button
                  class="text-sm margin-bottom-sm"
                  :class="item.value === where.kind ? 'bg-blue' : 'bg-blue light'"
                  style="width: 22%"
                  v-for="item in kindFilterList"
                  @click="chooseKindFilter(item)"
              >
                {{ item.name }}
              </button>
            </view>
            <button
                @click="gotoCollect"
                class="cu-btn bg-red"
                style="width: 80%;position: absolute; bottom: 10px; left: 50%;transform: translateX(-50%);z-index: 100"
            >
              我的收藏
            </button>
          </swiper-item>
          <swiper-item>
            <view class="cu-bar">
              <view class="action sub-title">
                <text class="text-xl text-bold text-blue">属性筛选</text>
                <text class="text-ABC text-blue">attribute</text>
              </view>
            </view>
            <view class="padding-lr-sm">
              <scroll-view scroll-y style="height: 400px;padding: 10px 0;">
                <view class="flex align-center flex-wrap padding-tb-sm" style="background-color: #182f4d">
                  <view
                      @click="chooseRestrain(0)"
                      style="width: 20%;"
                      class="flex justify-center margin-bottom-sm"
                  >
                    <view style="width: 80%;" class="flex justify-center align-center text-white">
                      ALL
                    </view>
                  </view>
                  <view
                      @click="chooseRestrain(item.id)"
                      v-for="item in restrainList" :key="item.id" style="width: 20%;"
                      class="flex justify-center margin-bottom-sm"
                  >
                    <view style="width: 80%;" class="flex justify-center align-center flex-direction">
                      <image :src="item.icon" style="width: 60rpx; height: 60rpx"></image>
                    </view>
                  </view>
                </view>
              </scroll-view>
            </view>
          </swiper-item>
        </swiper>
        <view class="indication">
          <block v-for="(item,index) in 3" :key="index">
            <image class="spot" src="/static/title1.png" v-if="cardCur===index"></image>
            <image class="spot" src="/static/title.png" v-else></image>
          </block>
        </view>
      </view>
    </TnPopup>
    <scroll-view
        scroll-y
        :style="{height: `calc(100vh - ${height}px)`, paddingBottom: safeBottom + 'px'}"
        style="background-color: #24325b;"
        :scroll-into-view="topItem"
        scroll-with-animation
        @scroll="handleScroll"
    >
      <view id="top"></view>
      <view class="tn-flex-row tn-flex-wrap" v-if="mode === 'pic'">
        <view
            @click="gotoDetail(item)"
            v-for="item in list"
            style="width: 250rpx;text-align: center;"
            class="tn-mb-sm tn-flex tn-flex-column justify-between"
        >
          <view
              style="
                width: 230rpx;
                height: 383rpx;
                position: relative;
                background-size: cover;
                background-repeat: no-repeat;
                background-position: center;
                margin: 0 auto;
                border-radius: 5px;
              "
              :style="{backgroundImage: `url(${item.half_img || item.head_img})`}">
            <view
                class="tn-text-center tn-text-sm tn-flex align-center justify-center"
                style="
                  position: absolute;
                  bottom: 0;
                  left: 0;
                  width: 100%;
                  background-color: rgba(32, 47, 78, .9);
                  padding: 10rpx 0;
                  color:#88b4fe;
                "
            >
              {{ item.def_name }}
            </view>
            <view
                class="tn-text-sm tn-flex align-center justify-between"
                style="
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  background-color: rgba(32, 47, 78, .5);
                  padding: 10rpx 0;
                  color:#88b4fe;
                "
                @click.stop=""
            >
              <view>ID: {{ item.id }}</view>
              <view @click.stop="changeCollect(item)">
                <TnIcon bold color="#E83A30" v-if="item.collect_flag" name="floral-fill" size="45"/>
                <TnIcon bold color="#E83A30" v-else name="floral" size="45"/>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view v-for="item in list" style="width: 710rpx;height: 250rpx; position: relative"
              class="tn-m-sm tn-flex tn-p-sm tn-blue-light_bg tn-radius">
          <view @click.stop="changeCollect(item)" style="position: absolute;top: 5px;right: 5px;z-index: 10">
            <TnIcon bold color="#E83A30" v-if="item.collect_flag" name="floral-fill" size="45"/>
            <TnIcon bold color="#E83A30" v-else name="floral" size="45"/>
          </view>
          <view
              @click="previewImg(item)"
              style="width: 180rpx; height: 210rpx;background-position: center;background-repeat: no-repeat;background-size:
              cover"
              :style="{backgroundImage: `url(${item.half_img || item.head_img})`}"
          >
          </view>
          <view style="width: calc(100% - 180rpx);position: relative"
                class="tn-p-sm tn-pt-xs tn-pb-xs flex flex-direction justify-between">
            <view class="tn-text-lg flex align-center">
              <image style="width: 50rpx;height: 50rpx" :src="filterRestrain(restrainList, item.type).icon"></image>
              <text class="margin-left-sm">{{ item.def_name }}(ID: {{ item.id }})</text>
            </view>
            <view class="tn-flex justify-between">
              <view>
                种族值: {{ calcRace(item.hp, item.atk, item.def, item.sp_atk, item.sp_def, item.spd) }}
              </view>
            </view>
            <view>
              专属技能: {{ item.proprietary_skill }}
            </view>
            <view style="position: absolute; right: 10px; bottom: 5px" class="flex flex-direction align-end">
              <button @click="gotoCapture(item)" class="cu-btn bg-blue sm" :disabled="!item.capture">查询捕捉</button>
              <button @click.stop="gotoDetail(item)" class="cu-btn bg-blue sm margin-top">详细信息</button>
            </view>
          </view>
        </view>
      </view>
      <view class="back" :style="{display: scrollTop > 500 ? 'flex' : 'none'}" @click.stop="scrollToTop">
        <TnIcon name="totop-simple" style="font-size: 25px"/>
      </view>
      <view class="tn-flex-center">
        <TnButton text @click="loadMore" debounce :disabled="showLoading">
          {{ status === 'loadmore' ? '点击加载更多' : status === 'loading' ? '正在加载' : '到底啦~' }}
        </TnButton>
      </view>
    </scroll-view>
    <loading-page :show="showLoading" @click.stop=""/>
    <suspended @tagClick="changeMode" icon-name="starry" font-size="30px"/>
  </view>
</template>

<script setup>
  import TnIcon from '@/uni_modules/tuniaoui-vue3/components/icon/src/icon.vue';
  import TnNavbar from '@/uni_modules/tuniaoui-vue3/components/navbar/src/navbar.vue';
  import TnButton from '@/uni_modules/tuniaoui-vue3/components/button/src/button.vue';
  import TnPopup from '@/uni_modules/tuniaoui-vue3/components/popup/src/popup.vue'
  import LoadingPage from '@/components/loadingPage.vue';
  import Suspended from "@/components/suspended.vue";
  import {useUniAppSystemRectInfo} from '@/uni_modules/tuniaoui-vue3/hooks/use-uniapp-system-rect-info';
  import {getCurrentInstance, onMounted, ref, nextTick, computed, reactive} from 'vue';
  import {calcRace, filterRestrain} from "@/utils/utils";
  import {getAd, setAd} from "@/storage/ad";
  import {getFreeNum, setFreeNum} from "@/storage/free_num";
  import {getNow} from "@/storage/now";

  const {
    proxy
  } = getCurrentInstance()

  const pmAvatar = __wxConfig.accountInfo.icon

  const showLoading = ref(false)

  const {height} = useUniAppSystemRectInfo().navBarInfo
  const safeBottom = ref(0)


  // 初始数据
  const list = ref([])
  // 分页数据
  const where = reactive({
    page: 1,
    type: 0,
    limit: 60,
    def_name: '',
    open_id: uni.getStorageSync('openid'),
    kind: '',
    collect_flag: true,
    sort: 'id',
    order: 'desc'
  })
  const totalPages = ref(0)
  const getList = async () => {
    showLoading.value = true;
    if (where.page === 1) {
      ({records: list.value, pages: totalPages.value} = await proxy.$api.getMonsterQuery(where))
    } else {
      const {records} = await proxy.$api.getMonsterQuery(where)
      list.value.push(...records)
    }
    showLoading.value = false
  }

  const showPopup = ref(false)

  const filterList = ref([{
    name: '总和↑',
    order: 'asc',
    sort: 'race'
  }, {
    name: '总和↓',
    order: 'desc',
    sort: 'race'
  }, {
    name: '攻击↑',
    order: 'asc',
    sort: 'atk'
  }, {
    name: '攻击↓',
    order: 'desc',
    sort: 'atk'
  }, {
    name: '特攻↑',
    order: 'asc',
    sort: 'sp_atk'
  }, {
    name: '特攻↓',
    order: 'desc',
    sort: 'sp_atk'
  }, {
    name: '防御↑',
    order: 'asc',
    sort: 'def'
  }, {
    name: '防御↓',
    order: 'desc',
    sort: 'def'
  }, {
    name: '特防↑',
    order: 'asc',
    sort: 'sp_def'
  }, {
    name: '特防↓',
    order: 'desc',
    sort: 'sp_def'
  }, {
    name: '速度↑',
    order: 'asc',
    sort: 'spd'
  }, {
    name: '速度↓',
    order: 'desc',
    sort: 'spd'
  }, {
    name: '体力↑',
    order: 'asc',
    sort: 'hp'
  }, {
    name: '体力↓',
    order: 'desc',
    sort: 'hp'
  }, {
    name: 'ID↑',
    order: 'asc',
    sort: 'id'
  }, {
    name: 'ID↓',
    order: 'desc',
    sort: 'id'
  }])

  const kindFilterList = ref([{
    name: '全部',
    value: ''
  },{
    name: 'pve',
    value: '0'
  },{
    name: '强攻',
    value: '1'
  },{
    name: '护盾',
    value: '2'
  },{
    name: '减伤',
    value: '3'
  },{
    name: '辅助',
    value: '4'
  },{
    name: '恢复',
    value: '5'
  },{
    name: '免伤',
    value: '6'
  },{
    name: '免疫异常',
    value: '7'
  },{
    name: '消回合',
    value: '8'
  },{
    name: '先制',
    value: '9'
  },{
    name: '控制',
    value: '10'
  },{
    name: '强化',
    value: '11'
  },{
    name: '弱化',
    value: '12'
  },{
    name: '封属',
    value: '13'
  },{
    name: '固伤',
    value: '14'
  },{
    name: '减pp',
    value: '15'
  },{
    name: '护罩',
    value: '16'
  },{
    name: '闪避',
    value: '17'
  },{
    name: '干扰',
    value: '18'
  }])

  const chooseKindFilter = async (item) => {
    where.kind = item.value
    await search()
  }

  const chooseFilter = (item) => {
    where.sort = item.sort
    where.order = item.order
    search()
  }

  // 触底触发
  const loadMore = async () => {
    if (status.value === 'loading') return
    if (status.value === 'loadmore') {
      where.page++
      await getList()
    } else {
      showLoading.value = false
    }
  }

  // 滚动触发
  const scrollTop = ref(0)
  const topItem = ref('')
  const handleScroll = (ev) => {
    scrollTop.value = ev.detail.scrollTop
    topItem.value = ''
  }

  // 返回顶部
  const scrollToTop = () => {
    nextTick(() => {
      topItem.value = 'top'
      scrollTop.value = 0
    })
  }

  // 搜索
  const search = async () => {
    where.page = 1
    showPopup.value = false
    await getList()
  }

  // 修改图鉴模式
  const mode = ref(uni.getStorageSync('mapMode') || 'pic')
  const changeMode = async () => {
    mode.value = mode.value === 'pic' ? mode.value = 'map' : mode.value = 'pic'
    uni.setStorageSync('mapMode', mode.value)
    await getList()
  }

  const status = computed(() => {
    if (showLoading.value) {
      return 'loading'
    } else if (where.page < totalPages.value) {
      return 'loadmore'
    } else {
      return 'nomore'
    }
  })

  // 跳转捕捉信息页
  const gotoCapture = (item) => {
    const now = new Date().getTime()
    if (getNow() && (now - getNow() > 48 * 60 * 60 * 1000)) {
      setAd(true)
    }
    const url = '/pages/jingling-capture/jingling-capture?data=' + JSON.stringify(item)
    if (getAd() && getFreeNum() === 0) {
      uni.navigateTo({
        url: '/pages/ad/ad?url=' + url
      })
    } else {
      let freeNum = getFreeNum()
      if (freeNum > 0) {
        freeNum--
        setFreeNum(freeNum)
      }
      uni.navigateTo({
        url
      })
    }
  }

  // 跳转详情页
  const gotoDetail = (item) => {
    const now = new Date().getTime()
    if (getNow() && (now - getNow() > 48 * 60 * 60 * 1000)) {
      setAd(true)
    }
    const url =
        `/pages/jingling-detail/jingling-detail?data= ${JSON.stringify(item)}`
    if (getAd() && getFreeNum() === 0) {
      uni.navigateTo({
        url: '/pages/ad/ad?url=' + encodeURIComponent(JSON.stringify(url))
      })
    } else {
      let freeNum = getFreeNum()
      if (freeNum > 0) {
        freeNum--
        setFreeNum(freeNum)
      }
      uni.navigateTo({
        url
      })
    }
  }

  // 预览图片
  const previewImg = (item) => {
    uni.previewImage({
      urls: [item.half_img, item.fight_img, item.head_img]
    })
  }

  // 获取属性列表
  const restrainList = ref([])
  const getRestrainList = async () => {
    restrainList.value = await proxy.$api.getRestrainList()
  }

  // 属性查找
  const chooseRestrain = (id) => {
    where.type = id
    search()
  }

  const cardCur = ref(0)
  const cardSwiper = (e) => {
    cardCur.value = e.detail.current
  }

  // 收藏/取消收藏
  const changeCollect = async (item) => {
    if (showLoading.value) return
    if (uni.getStorageSync('openid')) {
      try {
        showLoading.value = true
        await proxy.$api.saveCollect({
          open_id: uni.getStorageSync('openid'),
          type: 'monster',
          biz_id: item.id,
          action_type: item.collect_flag ? 'remove' : 'add',
          collect_ids: item.id
        })
        const title = item.collect_flag ? `${item.def_name}被移除了收藏o(╥﹏╥)o` : `${item.def_name}被加入了收藏(*^▽^*)`
        uni.showToast({
          title,
          icon: 'none',
          duration: 2500
        })
        item.collect_flag = !item.collect_flag
        list.value = list.value.filter(item => item.collect_flag)
        showLoading.value = false
      } catch (e) {
        showLoading.value = false
      }
    }
  }

  onMounted(async () => {
    uni.$on('changeCollectFlag', (data) => {
      list.value.forEach(item => {
        if(item.id === data.id) {
          item.collect_flag = data.collect_flag
        }
      })
    })
    uni.getSystemInfo({
      success: res => {
        safeBottom.value = res.safeAreaInsets.bottom
      }
    });
    await getList()
    await getRestrainList()
  })
</script>


<style scoped lang="scss">
  .more {
    position: fixed;
    right: 5px;
    bottom: 50px;
    z-index: 10001;

    .map {
      width: 50px;
      height: 50px;
      border-radius: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #01beff;
      color: #fff;
    }
  }

  .back {
    width: 50px;
    height: 50px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, .4);
    color: #fff;
    position: fixed;
    right: 5px;
    bottom: 120px;
    z-index: 10001;
  }

  @keyframes float {
    0% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-10px);
    }
    100% {
      transform: translateY(0);
    }
  }

  .indication {
    z-index: 11;
    width: 100%;
    height: 30px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .spot {
    // background-color: #FBBD12;
    opacity: 0.8;
    width: 20rpx;
    height: 20rpx;
    margin: 0 10rpx !important;
    left: 0;
    top: 0;
    position: relative;
    z-index: 12;
  }
</style>
